package ru.usu.gv.gui.analysis;

import ru.usu.gv.core.GraphCanvas;
import ru.usu.gv.graph.Graph;
import ru.usu.gv.uicomponents.UIEdge;
import ru.usu.gv.uicomponents.UIGraph;
import ru.usu.gv.uicomponents.UIVertex;
import ru.usu.gv.utils.GeometryUtil;

import javax.vecmath.Point3d;

import java.util.List;

/**
 @author Sergey Pupyrev 
 13.04.2007
 */

public class AngleEdgeAnalyzer extends GraphAnalyzer
{
	public AngleEdgeAnalyzer()
	{
		super(AnalysisPanel.getInstance().getAngleSlider());
	}

	@Override
	protected double calculateAnalysValue()
	{
		UIGraph uiGraph = GraphCanvas.getInstance().getCurrentGraph();
		Graph graph = uiGraph.getGraph();
		double d = 0;
		for (int i = 0; i < graph.getSize(); i++)
		{
			UIVertex v = uiGraph.getVertexes().get(i);
			double minAngle = 2.0 * Math.PI;

			List<UIEdge> edges = uiGraph.getEdges(v);
			for (int j = 0; j < edges.size(); j++)
				for (int k = j + 1; k < edges.size(); k++)
				{
					UIEdge edge1 = edges.get(j);
					UIEdge edge2 = edges.get(k);

					Point3d p1, p2;
					p1 = getNextPoint(v, edge1);
					p2 = getNextPoint(v, edge2);
					double cur = GeometryUtil.calculateAngle(v.getPosition(), p1, p2);
					if (minAngle > cur)
						minAngle = cur;
				}

			double meanValue = 2.0 * Math.PI / edges.size();
			d += (meanValue - minAngle) / meanValue;
		}

		d /= uiGraph.getGraph().getSize();
		return 1.0 - d;
	}

	private Point3d getNextPoint(UIVertex v1, UIEdge edge)
	{
		Point3d[] controlPoints = edge.getViewItem().getControlPoints();
		if (edge.getV1().equals(v1))
		{
			if (controlPoints.length == 0)
				return edge.getV2().getPosition();

			return controlPoints[0];
		}
		else
		{
			if (controlPoints.length == 0)
				return edge.getV1().getPosition();

			return controlPoints[controlPoints.length - 1];
		}
	}

}
